package service

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
	"time"
)

//自定义一个字符串
var jwtKey = []byte("www.topgoer.com")

type Claims struct {
	UserId int
	jwt.StandardClaims
}

//颁发token
func SetTingToken(userId int) string {
	expireTime := time.Now().Add(7 * 24 * time.Hour)
	claims := &Claims{
		UserId: userId,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(), //过期时间
			IssuedAt:  time.Now().Unix(),
			Issuer:    "127.0.0.1:8181", // 签名颁发者
			Subject:   "user token",     //签名主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	// fmt.Println(token)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		fmt.Println(err)
	}
	return tokenString
	//getStr = tokenString
	//ctx.JSON(200, gin.H{"token": tokenString})
}

//解析token
func GetTingToken(tokenString string) (int, string) {
	//tokenString := ctx.GetHeader("token")
	if tokenString == "" {
		return 0, "token not null"
	}
	token, claims, err := ParseToken(tokenString)
	if err != nil || !token.Valid {
		return 0, "token error"
	}
	return claims.UserId, "success"
}

func ParseToken(tokenString string) (*jwt.Token, *Claims, error) {
	Claims := &Claims{}
	token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token) (i interface{}, err error) {
		return jwtKey, nil
	})
	return token, Claims, err
}
